<?php

namespace app\common\model\game;

use app\common\model\Config;
use app\common\model\User;
use app\common\model\user\Viptype;
use think\Exception;
use think\Model;


class Groups extends Model
{


    // 表名
    protected $table = 'game_groups';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [

    ];


    public static function init()
    {
        self::beforeInsert(function ($row) {
            $info = self::where([
                "third_id" => $row['third_id']
            ])->find();
            if ($info) {
                throw new Exception("当前群聊已存在");
            }
        });

        self::beforeUpdate(function ($row) {
            $info = self::where([
                "third_id" => $row['third_id']
            ])->where("id", "neq", $row['id'])->find();
            if ($info) {
                throw new Exception("当前群聊已存在");
            }
        });
    }

    //房间门票价格
    public function deduction($user_id, $group_id)
    {
        $user = User::get($user_id);
        $room = $this->with(['modes', 'levels'])->find($group_id)->toArray();
        $price = $room['levels']['money'];//门票价格
        $server_ratio = Config::where('name', 'server_ratio')->value('value');//服务费比例
        $server_price = $price * $server_ratio / 100;//服务费
        if ($user['vip_end_time'] > time()) {
            $vip_ids = explode(",", $room['levels']['vip_ids']);
            if (in_array($user['vip_type_id'], $vip_ids)) {
                $ratio = Viptype::where('id', $user['vip_type_id'])->value('serve_discount');//折扣比例
                $server_price = $server_price * $ratio;
            }
        }
        return ['money' => $price, 'service' => $server_price];
//        return bcadd($price, $server_price, 2);
    }

    public function lists()
    {
        return $this->belongsTo('Lists', 'game_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function subarea()
    {
        return $this->belongsTo('Subarea', 'subarea_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function modes()
    {
        return $this->belongsTo('Modes', 'mode_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    //门票实际扣除费用

    public function levels()
    {
        return $this->belongsTo('Levels', 'level_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
}
